package com.example.demo.controller;

import com.example.demo.enums.Status;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
import com.example.demo.utill.ResponseResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import javax.annotation.Resource;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private HttpServletRequest servletRequest;
    @RequestMapping("/login")
    @ResponseBody
    public ResponseResult selectUser(String uname, String psd,HttpSession session){
        User user=userService.selectUser(uname,psd);
        ResponseResult res=new ResponseResult();
        if(user!=null){
            res.setData(user);
            res.setMessage("登陆成功");
            res.setStatus(Status.LOGIN_SUCCESS);
            res.setCode(200);
            session.setAttribute("userId",user.getId());
        }
        else{
            res.setCode(500);
            res.setStatus(Status.LOGIN_FAIL);
            res.setMessage("登录失败");
        }
        return res;
    }

    @RequestMapping("/reg")
    @ResponseBody
    public ResponseResult insertUser(String uname,String psd,String email,String code){
        HttpSession session=servletRequest.getSession();
        Object sCode=session.getAttribute("code");
        ResponseResult res=new ResponseResult();
        User name=userService.selectName(uname);
        if(name==null){
            if(sCode.equals(code)){
                userService.insertUser(uname,psd,email);
                res.setMessage("注册成功");
            }
            else {
                res.setMessage("验证码错误");
            }
        }else
        {
            res.setMessage("用户已经存在");
        }
        return res;
    }

    @RequestMapping("/search")
    @ResponseBody
    public ResponseResult search(String uname){
        User name=userService.selectName(uname);
        ResponseResult res=new ResponseResult();
        if(name!=null){
            res.setCode(500);
            res.setData(name);
        }else{
            res.setCode(200);
        }
        return res;
    }
}
